﻿using System;
using System.Collections.Generic;

using System.Text;
using System.Web;
using System.IO;
using System.Web.UI;

namespace Fly.Net.Static
{
    public class StaticPage
    {
        public virtual string Key
        {
            get;
            set;
        }

        public virtual string Version
        {
            get;
            set;
        }

        public virtual string Content
        {
            get;
            set;
        }

        public StaticPage(string key, string version)
        {
            Key = key;
            Version = version;
        }

        public Stream Stream { get; set; }
        protected TextWriter Writer { get; set; }
        protected HtmlTextWriter HtmlWriter { get; set; }

        public virtual HtmlTextWriter StartWrite()
        {
            if (Writer != null)
                throw new Exception("字符流已打开");

            Stream = new MemoryStream();
            Writer = new StreamWriter(Stream);
            return HtmlWriter = new HtmlTextWriter(Writer);
        }

        public virtual void CacheTo(ICache cacher)
        {
            cacher.Set(this.Key, this);
        }

        public virtual void EndWrite(ICache cacher)
        {
            EndWrite();
            CacheTo(cacher);
        }

        public virtual void EndWrite()
        {
            HtmlWriter.Flush();

            var reader = new StreamReader(Stream);
            Stream.Position = 0;
            this.Content = reader.ReadToEnd();

            HtmlWriter.Close();
            this.Stream.Close();

            this.HtmlWriter.Dispose();
            this.Writer.Dispose();
            this.Stream.Dispose();

        }

        public void ProcessRequest()
        {
            var response = HttpContext.Current.Response;

            var clientEtag = HttpContext.Current.Request.ServerVariables["HTTP_IF_NONE_MATCH"];
            if (!string.IsNullOrEmpty(clientEtag) && clientEtag.Equals(this.Version))
            {
                response.ClearHeaders();
                response.AppendHeader("Etag", this.Version);
                response.AppendHeader("Content-Length", "0");
                response.Status = "304 Not Modified";
                response.End();
                return;
            }


            response.ClearContent();
            response.Write(this.Content);
            response.AppendHeader("Etag", this.Version);
            response.End();
        }
    }
}
